package com.suntop.carousel.qlmediaplay.banner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;

import com.suntop.carousel.qlmediaplay.field.Field_Scale;
import com.suntop.carousel.qlmediaplay.media.IMediaPlayEventListener;
import com.suntop.carousel.qlmediaplay.media.IMediaPlayer;
import com.suntop.carousel.qlmediaplay.picture.QLPictureView;
import com.suntop.carousel.qlmediaplay.video.control.LiteControl;
import com.suntop.carousel.qlmediaplay.video.cover.ImageCover;
import com.suntop.carousel.qlmediaplay.video.player.QLVideoView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

public abstract class SingleBasicBanner<T> extends FrameLayout implements IMediaPlayEventListener {
    private QLVideoView mVideoView;
    private QLPictureView mPicture;
    private ArrayList<T> dateUrls = new ArrayList<>();
    private int mPosition = -1;//当前播放的下标
    private int mReady = -1;//已经处理好的下标

    public SingleBasicBanner(@NonNull Context context) {
        super(context);
        initView(context);
    }


    public SingleBasicBanner(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public SingleBasicBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @SuppressLint("NewApi")
    private void initView(Context context) {
        releaseView();
        mPicture = new QLPictureView(context);
        mVideoView = new QLVideoView(context);
        this.addView(mVideoView.getQLView(), LayoutParams.MATCH_PARENT
                , LayoutParams.MATCH_PARENT);
        this.addView(mPicture.getQLView(), LayoutParams.MATCH_PARENT
                , LayoutParams.MATCH_PARENT);
        intOption();
    }

    private void intOption() {
        mVideoView.addEventListener(this)
//                .init(0, 1)
                .autoCache(true)
                .addController(new LiteControl(getContext()))
                .setScaleType(Field_Scale.Scale_Match)
                .addIConView(new ImageCover(getContext()), true)
                .setDelayTime(5000);
        mPicture.addEventListener(this)
//                .init(0, 2)
                .setScaleType(Field_Scale.Scale_Match)
                .autoCache(true)
                .setDelayTime(5000);
    }

    public SingleBasicBanner setScaleType(int scaleType) {
        mPicture.setScaleType(scaleType);
        mVideoView.setScaleType(scaleType);
        return this;
    }

    public SingleBasicBanner setDelayTime(long time) {
        mPicture.setDelayTime(time);
        mVideoView.setDelayTime(time);
        return this;
    }

    public SingleBasicBanner setDate(ArrayList<T> arrayList) {
        this.dateUrls.clear();
        this.dateUrls.addAll(arrayList);
        mPosition = -1;//当前播放的下标
        mReady=-1;
        initFistView();
        return this;
    }

    /**
     * 判断是否需要创建
     * @param position 当前要播放的
     * @return
     */
    private boolean isNeedRebuildNow(int position){
        if (dateUrls.size()==0){
            return false;
        }
        //如果已经处理过了 那么不需要
        return mReady != position;

    }

    /**
     * 加载首页数据
     */
    private void initFistView() {
        if (dateUrls.size() == 0) {
            Log.e("SingleBanner", "handleMessage: 媒体列表为空");
            return;
        }
        mPosition=mPosition+1;
        boolean videoUrlPlay = initNextView(mPosition, true);
        if (videoUrlPlay) {
            mVideoView.getQLView().setVisibility(VISIBLE);
            mPicture.getQLView().setVisibility(GONE);
        } else {
            mPicture.getQLView().setVisibility(VISIBLE);
            mVideoView.getQLView().setVisibility(GONE);
        }
    }

    /**
     * 初始化下一个节目 如果可以
     *
     * @param position 下一个进度
     * @param isBuild  强制初始化
     * @return
     */
    @SuppressLint("NewApi")
    private boolean initNextView(int position, boolean isBuild) {
        if (dateUrls.size() == 0) {
            Log.e("SingleBanner", "handleMessage: 媒体列表为空");
            return false;
        }
        int realPosition = position;
        if (realPosition >= dateUrls.size()) {
            realPosition = 0;
        }
        T t = dateUrls.get(realPosition);
        boolean videoUrlPlay = isVideoUrlPlay(t);
        if (videoUrlPlay) {
            buildMediaUrl(mVideoView, t, realPosition, true);
            if (mVideoView.getQLView().getVisibility() == GONE) {
                mVideoView.build(false);
                mReady=realPosition;
            } else {
                if (isBuild) {
                    mVideoView.build(false);
                    mReady=realPosition;
                }
            }
        } else {
            buildMediaUrl(mPicture, t, realPosition, false);
            if (mPicture.getQLView().getVisibility() == GONE) {
                mPicture.build(false);
                mReady=realPosition;
            } else {
                if (isBuild) {
                    mVideoView.build(false);
                    mReady=realPosition;
                }
            }
        }
        return videoUrlPlay;
    }

    /**
     * T是泛型 整理数据
     *
     * @param mediaPlayer
     * @param t
     * @param position
     * @param isVideo
     */
    protected abstract void buildMediaUrl(IMediaPlayer mediaPlayer
            , T t, int position, boolean isVideo);

    /**
     * 表示是否视频
     *
     * @param t
     */
    protected abstract boolean isVideoUrlPlay(T t);



    private void startPlay(int position) {
        boolean b = initNextView(position, isNeedRebuildNow(position));
        if (b) {
            mVideoView.startPlay();
        } else {
            mPicture.startPlay();
        }
    }


    @Override
    public void startMediaPlay(int position, int type, String url) {
        if (type == 1) {
            mVideoView.getQLView().setVisibility(VISIBLE);
            mPicture.getQLView().setVisibility(GONE);
        } else {
            mPicture.getQLView().setVisibility(VISIBLE);
            mVideoView.getQLView().setVisibility(GONE);
        }
        mPosition=position;
        initNextView(this.mPosition + 1, false);
    }


    @Override
    public void cacheMediaPlay(int position, int type, String url, String path) {

    }

    @Override
    public void finishMediaPlay(int position, int type, String url, String error) {
        startPlay(mPosition+1);
    }

    public void startView() {
        startPlay(mPosition);
    }

    public void pauseView() {
        if (mPicture != null && mPicture.getQLView().getVisibility() == VISIBLE) {
            mPicture.stopPlay();
        }
        if (mVideoView != null && mVideoView.getQLView().getVisibility() == VISIBLE) {
            mVideoView.stopPlay();
        }
        mReady=-1;
    }


    /**
     * 释放控件
     */
    @SuppressLint("NewApi")
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void releaseView() {
        if (mPicture != null) {
            mPicture.releasePlay();
            this.removeView(mPicture.getQLView());
        }
        if (mVideoView != null) {
            mVideoView.releasePlay();
            this.removeView(mVideoView);
        }
        mPicture = null;
        mVideoView = null;
    }

}
